const request = require("request");
const path = require("path");
const localFunc = require(path.join(__dirname, "../core/function"))

function Search() {
    /**
     * db is arrayObject
     * each one is json. include `url`,`name`,`userName`,`userToken`,`searchStr`;
     */
    var db;
    this.init = function () {
        db = [];
    }
    this.setUrl = function (domain, userName, userToken) {
        var info = {};
        info.domain = domain;
        info.userName = userName;
        info.userToken = userToken;
        construct(info);
    }
    this.getAll = function() {
        return db;
    }
    //private
    function construct(info) {
        var url = localFunc.construcUrlByNameAndToken(info.userName, info.userToken, info.domain + "/api/json");
        request.get(url, function (error, response, body) {
            try {
                let data = JSON.parse(body);
                let jobs = data.jobs;
                for (let i = 0; i < jobs.length; i++) {
                    let elem = jobs[i];
                    let project = {};
                    project.url = elem.url;
                    project.name = elem.name;
                    project.userName = info.userName;
                    project.userToken = info.userToken;
                    project.searchStr = (elem.url + " " + elem.name).toLowerCase();
                    db.push(project);
                }
            }
            catch (e) {
                console.log("JSON parse error");
            }
        });
    }

    /**
     * search by str `aa bb cc`
     * @return array [],some of db
     */

    this.search = function (str) {
        var keywords = str.toLowerCase().split(" ");
        var ret = [];
        for (let i = 0; i < db.length; i++) {
            if(str.toLowerCase() == db[i].name.toLowerCase()) {
                ret.push(db[i]);
            }
        }
        for (let i = 0; i < db.length; i++) {
            var isFound = true;
            var searchStr = db[i].searchStr;
            for (let j = 0; j < keywords.length; j++) {
                if (searchStr.indexOf(keywords[j]) == -1) {
                    isFound = false;
                }
            }
            if (isFound) {
                ret.push(db[i]);
            }
        }
        return ret;
    }
}

//test start
// var o = new search();
// o.init();
// o.setUrl("http://build.navicore.cn", "mapbar", "f86f51987e9f910a84f77d5610d6f8e3");
// setTimeout(function () {
//     var res = o.search("NAVICORE TEST");
//     console.log(res);
// }, 1000);
//test end


/**
 * init --> seturl;
 * search(keywordStr)
 */
module.exports = Search;